import 'dart:io';
import 'dart:typed_data';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:wu_you/data/repository/home_repository.dart';
import 'package:wu_you/data/repository/user_repository.dart';
import 'package:wu_you/l10n/messages.dart';
import 'package:wu_you/model/user/user_model.dart';
import 'package:wu_you/page/dialog/custom_dialog.dart';
import 'package:wu_you/res/colors.dart';
import 'package:wu_you/state/bloc/http_bloc.dart';
import 'package:wu_you/state/bloc/user_bloc.dart';
import 'dart:ui' as ui;
import 'package:wu_you/utils/extension_utils.dart';
import 'package:wu_you/utils/cache_util.dart';
import 'package:wu_you/utils/utils.dart';
import 'package:wu_you/widgets/http_status_widget.dart';
import 'package:qr_flutter/qr_flutter.dart';
import 'package:share/share.dart';

class SharePage extends StatefulWidget{
  @override
  SharePageState createState() => SharePageState();
}
class SharePageState extends State<SharePage>{

  // final List<GlobalKey> _repaintWidgetKeys = [];
  final SwiperController _controller = SwiperController();
  GlobalKey rootWidgetKey = GlobalKey();
  List<String> list = ['share_one'];

  var future;
  String url;
  @override
  void initState() {
    super.initState();
    future = UserRepository().getShareCode();
    HomeRepository().getDownloadUrl().then((value) {
      setState(() {
        url = value.download_url;
      });
    });
  }

  var message;
  @override
  Widget build(BuildContext context) {
    message = AppLocalizations.of(context);
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        title: Text("${message['share1']}"),
        centerTitle: true,
        actions: [
          IconButton(
            icon: Icon(Icons.share_sharp),
            onPressed: _share,
          )
        ],
      ),
      body:HttpWidget<UserInfoModel, UserInfoBloc>(
          create: (context) => UserInfoBloc()..add(HttpEvent()),
          child: (context, data) {
            return Container(
              color: AppColors.dividerColor,
              width: double.infinity,
              height: double.infinity,
              child: SingleChildScrollView(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    AspectRatio(
                      aspectRatio: 0.68,
                      child: Padding(
                        padding: EdgeInsets.only(left: 18,right: 18,top: 12,bottom: 12),
                        child: RepaintBoundary(
                          key: rootWidgetKey,
                          child: Padding(
                            padding: EdgeInsets.only(left: 18,right: 18,top: 12,bottom: 12),
                            child: Stack(
                              fit: StackFit.expand,
                              children: [
                                ClipRRect(
                                  borderRadius: BorderRadius.all(Radius.circular(8)),
                                  child: Image.asset(Utils.getImgPath('share_one'),
                                    fit: BoxFit.fill,
                                  ),
                                ),
                                Positioned(
                                  bottom: 20,
                                  left: 15,
                                  right: 15,
                                  child: Container(
                                    // height: 90,
                                    child: FutureBuilder(
                                      future: future,
                                      builder: (context,data){
                                        String url = data.data;
                                        if(url != null){
                                          return Row(
                                            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                                            children: [
                                              Column(
                                                mainAxisSize: MainAxisSize.min,
                                                children: [
                                                  // Text("中文版"),
                                                  // SizedBox(height: 6,),
                                                  QrImage(
                                                    data: "$url"+"&language=zh",
                                                    size: 88,
                                                    padding: EdgeInsets.zero,
                                                    backgroundColor: Colors.white,
                                                  )
                                                ],
                                              ),
                                              // Column(
                                              //   mainAxisSize: MainAxisSize.min,
                                              //   children: [
                                              //     Text("English"),
                                              //     SizedBox(height: 6,),
                                              //     QrImage(
                                              //       data: "$url"+'&language=en',
                                              //       size: 72,
                                              //       padding: EdgeInsets.zero,
                                              //       backgroundColor: Colors.white,
                                              //     )
                                              //   ],
                                              // )
                                            ],
                                          );
                                        }else{
                                          return Container();
                                        }
                                      },
                                    ),
                                  ),
                                ),
                              ],
                            ),
                          ),
                        ),
                      ),
                    ),
                    Container(
                      padding: EdgeInsets.all(12),
                      margin: EdgeInsets.all(12),
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.all(Radius.circular(4)),
                        color: Colors.white,
                      ),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text(
                                "邀请码",
                                style: TextStyle(fontSize: 14, color: AppColors.textColor),
                              ),
                              Padding(
                                  padding: EdgeInsets.only(top: 12),
                                  child: Row(
                                    children: [
                                      Text(
                                        "${data.id}",
                                        style: TextStyle(
                                          fontSize: 16,
                                          color: AppColors.textColor,
                                          fontWeight: FontWeight.bold,
                                        ),
                                      ),
                                      SizedBox(width: 12,),
                                      // Text("${message['share3']}",style: TextStyle(fontSize: 15,color: AppColors.primaryColor),).addGesture(() {
                                      //   ClipboardData d = new ClipboardData(text: "${data.id}");
                                      //   Clipboard.setData(d);
                                      //   ToastUtils.show("${message['share4']}", context);
                                      // })
                                    ],
                                  )
                              ),
                            ],
                          ),
                          ElevatedButton(
                            onPressed: () {
                              ClipboardData d = new ClipboardData(text: "${data.id}");
                              Clipboard.setData(d);
                              ToastUtils.show("${message['share4']}", context);
                              // showDialog(context: context, builder: (context){
                              //   return HuaLuoDialog();
                              // }).then((value){
                              //   if(value != null){
                              //     LoadingApi.func(UserRepository().getHualuoCode(value), context,complete: (v){
                              //       showDialog(context: context, builder: (context){
                              //         return TeamCodeView(url: v,);
                              //       });
                              //     },error: (e){
                              //       ToastUtils.show("$e", context);
                              //     });
                              //   }
                              // });
                            },
                            child: Text("${message['share3']}"),
                            style: ButtonStyle(
                              minimumSize: MaterialStateProperty.all(Size(98, 36)),
                            ),
                          )
                        ],
                      ),
                    ),
                    // Padding(
                    //   padding: EdgeInsets.all(12),
                    //   child: Text(
                    //     "${message['share5']}：\n${message['share6']}",
                    //     style: TextStyle(color: AppColors.textColor, fontSize: 13),
                    //   ),
                    // ),
                    // Padding(
                    //   padding: EdgeInsets.only(left: 6,top: 6,right: 12,bottom: 6),
                    //   child: Column(
                    //     crossAxisAlignment: CrossAxisAlignment.start,
                    //     children: [
                    //       Text("${message['share8']}",style: TextStyle(color: AppColors.textColor, fontSize: 13)),
                    //       Row(
                    //         children: [
                    //           Expanded(child: Text("${url}")),
                    //           SizedBox(width: 20,),
                    //           Text("${message['share3']}",style: TextStyle(color: AppColors.primaryColor,fontSize: 14),).addGesture(() {
                    //             ClipboardData d = new ClipboardData(text: "$url");
                    //             Clipboard.setData(d);
                    //             ToastUtils.show("${message['share4']}", context);
                    //           })
                    //         ],
                    //       )
                    //     ],
                    //   )
                    // ),

                    Padding(
                      padding: EdgeInsets.all(6),
                      child: Text(
                        "邀请步骤：\n分享邀请海报发给好友，好友通过邀请海报注册并下载APP成为您的直推用户。"
                         ,style: TextStyle(color: AppColors.textColor, fontSize: 13),
                      ),
                    )
                  ],
                ),
              )
            );
          }
       )
    );
  }


  Widget _buildShareContent(UserInfoModel data) {
    // list.forEach((element) {
    //   _repaintWidgetKeys.add(GlobalKey());
    // });
    return ClipRRect(
      borderRadius: BorderRadius.all(
        Radius.circular(8),
      ),
      child: RepaintBoundary(
        key: rootWidgetKey,
        child: Stack(
          fit: StackFit.expand,
          children: [
            Image.asset(Utils.getImgPath('share_one'),
              fit: BoxFit.fill,
            ),
            Positioned(
              bottom: 0,
              left: 8,
              right: 8,
              child: Container(
                margin: EdgeInsets.only(bottom: 20),
                padding: EdgeInsets.all(12),
                height: 90,
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(5),
                  color: Color.fromARGB(125, 255, 255, 255),
                ),
                child: Row(
                  children: [
                    FutureBuilder(
                      future: future,
                      builder: (context,data){
                        String url = data.data;
                        if(url != null){
                          return QrImage(
                            data: "$url",
                            size: 60,
                            padding: EdgeInsets.zero,
                            backgroundColor: Colors.white,
                          );
                        }else{
                          return QrImage(
                            data: "我是邀请二维码",
                            size: 60,
                            padding: EdgeInsets.zero,
                            backgroundColor: Colors.white,
                          );
                        }
                      },
                    ),
                    Padding(
                      padding: EdgeInsets.only(left: 12),
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            "${data.username.length > 11 ? data.username.substring(0,11)+"..." : data.username}",
                            style: TextStyle(fontSize: 14, color: AppColors.textColor),
                          ),
                          Text(
                            "推广码：${data.id}",
                            style: TextStyle(fontSize: 14, color: AppColors.textColor),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }


  Future<void> _share() async {
    // if (_repaintWidgetKeys.length == 0) {
    //   return;
    // }
    ///获取索引
    var index = _controller.index ?? 0;

    ///生成图片二进制数据
    RenderRepaintBoundary boundary = rootWidgetKey.currentContext.findRenderObject();
    double dpr = ui.window.devicePixelRatio; // 获取当前设备的像素比
    ui.Image image = await boundary.toImage(pixelRatio: dpr);
    ByteData _byteData = await image.toByteData(format: ui.ImageByteFormat.png);

    ///保存图片
    Uint8List sourceBytes = _byteData.buffer.asUint8List();
    String path = await CacheUtil.getShareImagePath("${DateTime.now().microsecond}.jpg");
    File file = new File(path);
    if (!file.existsSync()) {
      file.createSync(recursive: true);
    }
    file.writeAsBytesSync(sourceBytes);
    Share.shareFiles([path]);
  }
}



class HuaLuoDialog extends StatefulWidget{
  @override
  HuaLuoDialogState createState() => HuaLuoDialogState();
}
class HuaLuoDialogState extends State<HuaLuoDialog>{
  final _codeController = TextEditingController();
  var message;
  @override
  Widget build(BuildContext context) {
    message = AppLocalizations.of(context);
    return Material(
      color: Colors.transparent,
      child: WillPopScope(
        child: Center(
          child: Padding(
              padding: EdgeInsets.only(left: 40, right: 40),
              child: Container(
                  margin: EdgeInsets.only(bottom: 8),
                  decoration: BoxDecoration(
                      borderRadius: BorderRadius.all(Radius.circular(8)),
                      color: Colors.white
                  ),
                  child: Column(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Container(
                        margin: EdgeInsets.only(top: 15),
                        child: Text("${message['share7']}",style: TextStyle(fontSize: 16,fontWeight: FontWeight.bold),)
                      ),
                      Container(
                        margin: EdgeInsets.only(top: 15),
                        padding: EdgeInsets.only(left: 20,right: 20),
                        child: TextField(
                            controller: _codeController,
                            style: TextStyle(fontSize: 14, color: AppColors.textColor),
                            // maxLength: 11,
                            keyboardType: TextInputType.phone,
                            decoration: InputDecoration(
                              border: OutlineInputBorder(borderRadius: BorderRadius.circular(5.0), borderSide: BorderSide()),
                              counterText: '',
                              hintText: "${message['enterPhone']}",
                              hintStyle: TextStyle(
                                fontSize: 14,
                                color: AppColors.textHintColor,
                              ),
                              suffixIconConstraints: BoxConstraints.loose(Size(100, 56)),
                            )
                        ),
                      ),
                      SizedBox(height: 15,),
                      Divider(),
                      Row(
                        children: [
                          Flexible(
                              flex: 1,
                              child: Container(
                                width: double.infinity,
                                height: 50,
                                decoration: BoxDecoration(
                                  color: Colors.white,
                                  borderRadius: BorderRadius.only(
                                    bottomLeft: Radius.circular(8),
                                  ),
                                ),
                                alignment: Alignment.center,
                                child: Text("${message['product26']}",style: TextStyle(color: HexColor("#999999"),fontSize: 16),),
                              ).addGesture(() {
                                Navigator.of(context).pop();
                              })
                          ),
                          ColoredBox(color: HexColor("#E8E8E8"),
                            child: SizedBox(width: 1,height: 50,),
                          ),
                          Flexible(
                              flex: 1,
                              child: Container(
                                width: double.infinity,
                                height: 50,
                                decoration: BoxDecoration(
                                  color: Colors.white,
                                  borderRadius: BorderRadius.only(
                                    bottomRight: Radius.circular(8),
                                  ),
                                ),
                                alignment: Alignment.center,
                                child: Text("${message['product27']}",style: TextStyle(color: AppColors.primaryColor,fontSize: 16),),
                              ).addGesture(() {
                                if(_codeController.text == ""){
                                  ToastUtils.show("${message['enterPhone']}", context);
                                  return;
                                }
                                Navigator.of(context).pop(_codeController.text);
                              })
                          )
                        ],
                      )
                    ],
                  )
              )
          ),
        ),
        onWillPop: () async {
          return true;
        },
      ),
    );
  }
}